package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.comment.ResultCode;
import com.qianying.entity.Region;
import com.qianying.mapper.RegionMapper;
import com.qianying.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {

    @Autowired
    RegionMapper regionMapper;

    @Override
    public CommonResult<?> saveRegion(Region region) {
        try {
            region.setId(null);
            boolean success = save(region);
            if (success) {
                return CommonResult.success(region.getId(), "增加成功！");
            } else {
                return CommonResult.failed("保存失败");
            }
        } catch (Exception e) {
            return CommonResult.failed("保存异常：" + e.getMessage());
        }
    }

    @Override
    public CommonResult<?> updateRegion(Region region) {
        try {
            boolean success = updateById(region);
            if (success) {
                return CommonResult.success(region, "更新成功！");
            } else {
                return CommonResult.failed("更新失败");
            }
        } catch (Exception e) {
            return CommonResult.failed("更新异常：" + e.getMessage());
        }
    }

    @Override
    public CommonResult<?> deleteRegion(Long id) {
        try {
            boolean success = removeById(id);
            return success ? CommonResult.success("删除成功！") : CommonResult.failed("删除失败");
        } catch (Exception e) {
            return CommonResult.failed("删除异常：" + e.getMessage());
        }
    }

    @Override
    public CommonResult<Region> getRegionById(Long id) {
        try {
            Region region = getById(id);
            return CommonResult.success(region);
        } catch (Exception e) {
            return CommonResult.failed("查询异常：" + e.getMessage());
        }
    }

    @Override
    public CommonResult<?> listRegions() {
        try {
            return CommonResult.success(list());
        } catch (Exception e) {
            return CommonResult.failed("查询异常：" + e.getMessage());
        }
    }

    @Override
    public CommonResult<?> pageRegions(Integer pageNum, Integer pageSize) {
        try {
            Page<Region> page = page(new Page<>(pageNum, pageSize));
            return CommonResult.success(page);
        } catch (Exception e) {
            return CommonResult.failed("分页查询异常：" + e.getMessage());
        }
    }

    @Override
    public CommonResult<?> listByCustomerId(Long customerId) {
        try {
            if (customerId == null) {
                return CommonResult.failed("查询异常：id 为空！");
            }
            List<Region> list = regionMapper.listByCustomerId(customerId);
            if (list.isEmpty()) {
                return CommonResult.successEmpty();
            }

            return CommonResult.success(list, "获取数据成功！");
        } catch (Exception e) {
            return CommonResult.failed("查询异常：" + e.getMessage());
        }
    }

    @Override
    public CommonResult<Map<Long, String>> getRegionMapByCustomerId(Long customerId) {
        // 查询关联的大区列表
        CommonResult<?> regionsRes = listByCustomerId(customerId);

        if (!regionsRes.isSuccess()) {
            return CommonResult.failed("失败！");
        }
        List<Region> regions = (List<Region>) regionsRes.getData();
        // 转换为 Map<大区ID, 大区名称>
        Map<Long, String> regionMap = new HashMap<>();
        for (Region region : regions) {
            regionMap.put(region.getId(), region.getRegionName());
        }

        return CommonResult.success(regionMap);
    }

    @Override
    public Map<Long, String> getRegionMap() {
        // 查询所有大区记录
        List<Region> regions = regionMapper.selectList(null);

        // 处理空列表情况
        // 处理空列表情况
        if (regions == null || regions.isEmpty()) {
            return new HashMap<>(0);
        }

        // 转换为ID-名称映射Map
        return regions.stream()
                .collect(Collectors.toMap(
                        Region::getId,          // 键：大区ID
                        Region::getRegionName,  // 值：大区名称
                        (existing, replacement) -> existing  // 处理ID重复（保留第一条）
                ));
    }
}